package org.ghost.wechat.platform.common.filter;

import org.ghost.wechat.platform.common.component.RequestContext;
import org.ghost.wechat.platform.common.log.RequestPatternLayoutEncoder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 */
public class RequestUUIDFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {

        // uuid埋点
        uuidBuried((HttpServletRequest) req, (HttpServletResponse) res);

        chain.doFilter(req, res);
    }

    private void uuidBuried(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getHeader(RequestPatternLayoutEncoder.REQUEST_PATTERN);
        if (id == null || "".equals(id)) {
            id = UUID.randomUUID().toString();
        }

        RequestContext.getContext().setId(id);
        response.setHeader(RequestPatternLayoutEncoder.REQUEST_PATTERN, id);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
